package net.lab1024.sa.admin.module.app.api.login;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.extra.servlet.ServletUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import net.lab1024.sa.admin.constant.AdminSwaggerTagConst;
import net.lab1024.sa.admin.module.app.api.login.domain.AppLoginForm;
import net.lab1024.sa.admin.module.app.api.login.domain.AppLoginResultVO;
import net.lab1024.sa.admin.util.AppRequestUtil;
import net.lab1024.sa.base.common.annoation.AppRestController;
import net.lab1024.sa.base.common.annoation.NoNeedLogin;
import net.lab1024.sa.base.common.constant.RequestHeaderConst;
import net.lab1024.sa.base.common.domain.ResponseDTO;
import net.lab1024.sa.base.common.util.SmartRequestUtil;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

/**
 * app登录
 */
@AppRestController
@Tag(name = AdminSwaggerTagConst.App.APP_API_LOGIN)
public class AppLoginController {

    private final AppLoginService appLoginService;

    public AppLoginController(AppLoginService appLoginService) {
        this.appLoginService = appLoginService;
    }

    @NoNeedLogin
    @Operation(summary = "登录")
    @PostMapping("/login")
    public ResponseDTO<AppLoginResultVO> login(@Valid @RequestBody AppLoginForm form, HttpServletRequest request) {
        String ip = ServletUtil.getClientIP(request);
        String userAgent = ServletUtil.getHeaderIgnoreCase(request, RequestHeaderConst.USER_AGENT);
        return appLoginService.login(form, ip, userAgent);
    }

    @GetMapping("/login/getLoginInfo")
    @Operation(summary = "获取登录结果信息")
    public ResponseDTO<AppLoginResultVO> getLoginInfo() {
        AppLoginResultVO loginResult = appLoginService.getLoginResult(AppRequestUtil.getRequestAppUser());
        String tokenValue = StpUtil.getTokenValue();
        loginResult.setToken(tokenValue);
        return ResponseDTO.ok(loginResult);
    }

    @Operation(summary = "退出登陆")
    @GetMapping("/login/logout")
    public ResponseDTO<String> logout(@RequestHeader(value = RequestHeaderConst.TOKEN, required = false) String token) {
        return appLoginService.logout(token, SmartRequestUtil.getRequestUser());
    }

    @GetMapping("/login/test")
    public ResponseDTO<String> test() {
        return ResponseDTO.ok("test");
    }
}
